//
//  InitializingViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/8.
//

import UIKit
import RxSwift
import RxCocoa
import FBSDKCoreKit
import Alamofire
struct InitializeDataModel: Codable {
    
    struct FBDataModel: Codable {
        let fed: String
        let strengthening: String
        let putrid: String
        let cape: String
    }
    
    struct NationalFlag: Codable {
        let areaCode: String
        let countryFlag: String
    }
    
    let gallant: Int
    let national_flag: NationalFlag
    let curries: FBDataModel
}

class InitializingViewController: UIViewController {

    @IBOutlet weak var retryButton: UIButton!
    
    private let bag = DisposeBag()
    
    let disconnected = PublishSubject<Bool>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.disconnected
            .observe(on: MainScheduler.instance)
            .map({!$0})
            .subscribe(onNext: { [weak self] disconnected in
                self?.getInitializeData()
            })
            .disposed(by: self.bag)
        self.getInitializeData()
        self.retryButton
            .rx.tap
            .subscribe { [weak self] _ in
                self?.getInitializeData()
            }
            .disposed(by: self.bag)
        // Do any additional setup after loading the view.
    }
    
    //走初始化接口
    private func getInitializeData() {
        Task {
            do {
                let language = Locale.preferredLanguages.first ?? ""
                let proxy = DeviceManager.defalult.isProxy
                let isVPN = DeviceManager.defalult.isVPN
                let param = [
                    "counted": language,
                    "vitals": proxy ? 1 : 0,
                    "stap": isVPN ? 1 : 0
                ]
                let res = try await HTTPManager.default.get(path: Api.initialize, param: param, dataType: InitializeDataModel.self)
                if res.code == 0 {
                    HTTPManager.default.config = res.data
                    UserDefaults.standard.set(res.data?.gallant, forKey: "gallant")
                    Settings.shared.appID = res.data!.curries.strengthening
                    Settings.shared.clientToken = res.data!.curries.cape
                    Settings.shared.displayName = res.data!.curries.putrid
                    Settings.shared.appURLSchemeSuffix = res.data!.curries.fed
                    Settings.shared.isAdvertiserTrackingEnabled = true
                }
                let notFresher = UserDefaults.standard.bool(forKey: "notfresher")
                if (notFresher) {
                    let mainVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()!
                    let window = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first
                    let transaction = CATransition()
                    transaction.type = .fade
                    window?.rootViewController = mainVC
                    window?.layer.add(transaction, forKey: nil)
                } else {
                    let loadingVC = LoadingViewController()
                    let window = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first
                    let transaction = CATransition()
                    transaction.type = .fade
                    window?.rootViewController = loadingVC
                    window?.layer.add(transaction, forKey: nil)
                }
                //进入主界面
            } catch {
                let result = HTTPManager.default.switchServer()
                if (result) {
                    self.getInitializeData()
                } else {
                    do {
                        try await HTTPManager.default.enumerateServer()
                        let res = HTTPManager.default.switchServer()
                        if (res) {
                            self.getInitializeData()
                        }
                    } catch {
                        
                    }
                }
            }
        }
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
